<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>款式管理</span>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="query-form">
      <el-form-item label="款式名称">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入款式名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 120px">
          <el-option label="女" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="通用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        :data="groupedData"
        v-loading="loading"
        border
        :span-method="objectSpanMethod"
        style="width: 100%"
    >
      <!-- 款式列 -->
      <el-table-column
          prop="name"
          label="款式名称"
          align="center"
          header-align="center"
          min-width="200"
      />
      <!-- 性别列 -->
      <el-table-column
          label="性别"
          align="center"
          header-align="center"
          width="100"
      >
        <template #default="scope">
          {{ getGenderText(scope.row.genderLimit) }}
        </template>
      </el-table-column>
      <!-- 图片列 -->
      <el-table-column
          label="图片"
          align="center"
          header-align="center"
          width="120"
      >
        <template #default="scope">
          <el-image 
            v-if="scope.row.isFirstRow && scope.row.image" 
            :src="scope.row.image" 
            style="width: 80px; height: 80px"
            fit="cover"
            :preview-src-list="[scope.row.image]"
          />
        </template>
      </el-table-column>
      <!-- 尺码列 -->
      <el-table-column
          label="尺码"
          align="center"
          header-align="center"
          width="120"
      >
        <template #default="scope">
          {{ scope.row.sizeItem ? scope.row.sizeItem.size : '-' }}
        </template>
      </el-table-column>
      <!-- 尺码描述列 -->
      <el-table-column
          label="尺码说明"
          align="center"
          header-align="center"
          min-width="200"
          show-overflow-tooltip
      >
        <template #default="scope">
          {{ scope.row.sizeItem ? scope.row.sizeItem.description : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <template v-if="scope.row.isFirstRow">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.limit"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="款式名称">
          <el-input v-model="editForm.name" placeholder="请输入款式名称" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editForm.genderLimit" placeholder="请选择性别">
            <el-option label="女" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="通用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="款式图片">
          <el-upload
              class="avatar-uploader"
              :action="''"
              :show-file-list="false"
              :http-request="handleUpload"
              :before-upload="beforeUpload"
          >
            <img v-if="editForm.image" :src="editForm.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div style="color: #999; font-size: 12px; margin-top: 5px;">支持 jpg/png 格式，大小不超过 2MB</div>
        </el-form-item>
        
        <!-- 尺码信息 -->
        <el-divider>尺码信息</el-divider>
        <el-form :inline="true" :model="sizeForm" size="small">
          <el-form-item label="尺码" style="width: 200px">
            <el-input v-model="sizeForm.size" placeholder="如：M, 170/88A" style="width: 150px" />
          </el-form-item>
          <el-form-item label="尺码说明" style="width: 100%">
            <el-input 
              v-model="sizeForm.description" 
              placeholder="如：适合身高170-175cm" 
              style="width: 100%" 
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="addSize">添加</el-button>
          </el-form-item>
        </el-form>

        <!-- 尺码列表 -->
        <el-table :data="editForm.sizes" style="width: 100%; margin-top: 10px" size="small" border>
          <el-table-column prop="size" label="尺码" width="120" />
          <el-table-column prop="description" label="尺码说明" show-overflow-tooltip />
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button type="danger" size="small" @click="removeSize($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { _getClothingStylePage, _deleteClothingStyle, _getClothingStyleById, _updateClothingStyle } from '@/api/clothingStyle'
import { _uploadFile } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 查询条件
const queryParams = ref({
  page: 1,
  limit: 10,
  name: '',  // 修改为styleName -> name
  gender: null  // 修改为字符串 -> Byte类型
})

// 表格数据
const groupedData = ref([])
const spanArr = ref([]) // 存储合并规则
const total = ref(0)
const loading = ref(false)

// 编辑对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editForm = ref({
  id: null,
  name: '',  // 修改为styleName -> name
  genderLimit: null,  // 修改为gender -> genderLimit (Byte类型)
  image: '',  // 新增图片字段
  sizes: []
})

// 尺码信息表单（只保留size和description）
const sizeForm = ref({
  size: '',
  description: ''
})

// 查询列表
const getList = () => {
  loading.value = true
  _getClothingStylePage(queryParams.value).then(res => {
    if (res.code === 200) {
      // 处理数据：将sizes数组拆分为多行
      processTableData(res.data.records)
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch(err => {
    ElMessage.error('查询失败')
  }).finally(() => {
    loading.value = false
  })
}

// 处理表格数据，将sizes数组拆分为多行
const processTableData = (rawData) => {
  groupedData.value = []
  spanArr.value = []
  
  rawData.forEach(item => {
    const sizes = item.sizes || []
    const rowCount = sizes.length > 0 ? sizes.length : 1
    
    if (sizes.length === 0) {
      // 没有尺码数据，只显示一行
      groupedData.value.push({
        id: item.id,
        name: item.name,  // 修改字段名
        genderLimit: item.genderLimit,  // 修改字段名
        image: item.image,  // 新增图片字段
        sizeItem: null,
        isFirstRow: true
      })
      spanArr.value.push({ rowspan: 1, colspan: 1 })
    } else {
      // 有尺码数据，拆分为多行
      sizes.forEach((size, index) => {
        groupedData.value.push({
          id: item.id,
          name: item.name,  // 修改字段名
          genderLimit: item.genderLimit,  // 修改字段名
          image: item.image,  // 新增图片字段
          sizeItem: size,
          isFirstRow: index === 0 // 标记是否为组内第一行
        })
        // 记录合并规则：第一行合并rowCount行，其余行合并为0
        if (index === 0) {
          spanArr.value.push({ rowspan: rowCount, colspan: 1 })
        } else {
          spanArr.value.push({ rowspan: 0, colspan: 0 })
        }
      })
    }
  })
}

// 合并单元格方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 合并前3列（款式名称、性别、图片）
  if (columnIndex < 3) {
    return spanArr.value[rowIndex]
  }
}

// 性别转换函数：Byte -> 文字
const getGenderText = (genderLimit) => {
  const genderMap = {
    0: '女',
    1: '男',
    2: '通用'
  }
  return genderMap[genderLimit] || '-'
}

// 查询按钮
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置按钮
const resetQuery = () => {
  queryParams.value = {
    page: 1,
    limit: 10,
    name: '',
    gender: null
  }
  getList()
}

// 编辑按钮
const handleEdit = (row) => {
  loading.value = true
  _getClothingStyleById(row.id).then(res => {
    if (res.code === 200) {
      dialogTitle.value = '编辑款式'
      const data = res.data.clothingStyle
      editForm.value = {
        id: data.id,
        name: data.name,
        genderLimit: data.genderLimit,
        image: data.image || '',
        sizes: data.sizes || []
      }
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  }).finally(() => {
    loading.value = false
  })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认删除该款式吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    _deleteClothingStyle(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
  })
}

// 添加尺码
const addSize = () => {
  if (!sizeForm.value.size) {
    ElMessage.warning('请填写尺码')
    return
  }
  editForm.value.sizes.push({ ...sizeForm.value })
  sizeForm.value = {
    size: '',
    description: ''
  }
}

// 删除尺码
const removeSize = (index) => {
  editForm.value.sizes.splice(index, 1)
}

// 图片上传前的校验
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const handleUpload = async (options) => {
  const { file } = options
  
  try {
    const res = await _uploadFile(file)
    if (res.code === 200) {
      // 假设后端返回的数据格式为 { url: '图片地址' }
      editForm.value.image = res.data.url || res.data.data || res.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.message || '图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
  }
}

// 提交编辑
const submitEdit = () => {
  if (!editForm.value.name) {
    ElMessage.warning('请填写款式名称')
    return
  }
  if (editForm.value.genderLimit === null || editForm.value.genderLimit === undefined) {
    ElMessage.warning('请选择性别')
    return
  }
  
  // 处理尺码数据：移除id字段，保留styleId，因为后端使用逻辑删除，需要重新插入新记录
  const submitData = {
    ...editForm.value,
    sizes: editForm.value.sizes.map(size => ({
      styleId: editForm.value.id,  // 传递款式ID
      size: size.size,
      description: size.description
      // 不传递 id 字段，后端会自动生成新的主键ID
    }))
  }
  
  _updateClothingStyle(submitData).then(res => {
    if (res.code === 200) {
      ElMessage.success('更新成功')
      dialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  })
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.value.page = page
  getList()
}

const handleSizeChange = (size) => {
  queryParams.value.limit = size
  queryParams.value.page = 1
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .query-form {
    margin-bottom: 20px;
  }
}

// 图片上传样式
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>